<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 商家中心 注册、登陆、餐饮活动管理
 *
 * @package controller
 * @author aaron <andy1219111@>63.com
 * @version id:1.0 2014-05-16
 */
class store extends CI_Controller {

	const SLAVE_PAGE_SIZE = 10;
	const BATCH_SALT = "24ywm_photos_salt";
	//flash session salt
	const FlASH_SESS_SALT = "24ywm_manager_uploads";
	private $shop_dir = "shop";
	//订单每页显示的条数
	const ORDER_PAGE_SIZE = 200;
	const FOOD_PAGE_SIZE = 10;
	//初始化
	public function __construct(){
		// error_reporting(0);
		parent::__construct();
		$this->load->library('Layout');
		$this->layout->setLayout('shop/layout');
		$this->data['user_info'] = $this->session->userdata('user_info');
		$this->data['is_login'] = $this->data['user_info']['c_id'] ? true : false;
		if($this->data['is_login'] == true)
		{
			$this->data['ismain'] = $this->data['user_info']['ismain'];
		}
		//加载辅助函数
		$this->load->helper('MY_url');
		$this->load->helper('util');
		$this->lang->load('shop','chinese'); 
		$this->data['seo']['title'] = "商家管理";
		$this->data['seo']['description'] = "要外卖";
		$this->data['seo']['keywords'] = "要外卖";
	}
	/**
	 * 商家登陆 view 
	 * @param $s_name 商家名称
	 * @param $s_pwd 商家密码
	 * @author wenhuijang@sina.com
	 * @return null
	 */
	public function login(){
		$c_id = isset($this->data['user_info']['c_id']) ? $this->data['user_info']['c_id'] : "";
		if(is_numeric($c_id) && $c_id >0){
			alert_redirect(site_url('admin/index'));
			return;
		}
		$this->data['active'] = 'login';
		//$this->load->view('shop_register',$this->data);
		$this->layout->setLayout('layout');
		$this->data['is_login'] = false;
		$this->data['seo']['title'] = "商家登录";
		log_message('debug', '商户登录');
		$this->layout->view('shop_register',$this->data);	
		return;
	}

	public function signin(){
		//post 参数处理
		//print_r($_POST);
		//print_r($_GET);
		
		$data = array();
		//$data['username'] = htmlspecialchars($this->input->post('username'),ENT_QUOTES);
		//$data['password'] = $this->input->post('password');
		
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);
			$data['username'] = $postdata['username'];
			$data['password'] = $postdata['password'];		
		}else{
			$data['username'] = $_POST['username'];
			$data['password'] = $_POST['password'];
		}
		
		if(empty($data['username']) || empty($data['password'])){
			echo json_encode(array('success'=>0,'err_info'=>'username or password is null'));
			return;
		}

		//加载model
		$this->load->model('shop_model','shop');
		//用户名为电话号码、邮箱、字符名称

		$shop_info = $this->shop->get_shop_users(array('U.cuname'=>$data['username']));
		//用户不存在
		if(empty($shop_info) || $shop_info['password'] != md5($data['password'])){
			echo json_encode(array('success'=>0,'err_info'=>$this->lang->line('LOGIN_ERR')));
			return;
		}
		//商家是否待审核
		if($shop_info['confirm'] == -1){
			echo json_encode(array('success'=>0,'err_info'=>$this->lang->line('IS_CONFIRM')));
			return;
		}
		//session
		$session_data = array(
			'c_id' => $shop_info['cid'],
			'c_name' =>$shop_info['cname'],
			'c_type' => $shop_info['ctype'],
			'cuname' => $shop_info['cuname'],
			'c_uid' =>$shop_info['cuid'],
			'c_utype' =>$shop_info['cutype'],
			'ismain' =>$shop_info['ismain'],
			'speed'=>$shop_info['speed']
		);
		$this->session->set_userdata(array('user_info'=>$session_data));
		$this->log_model->storelog('商铺登录','');
		//更新登录时间
		$this->shop->update(array('lastlogin'=>date('Y-m-d H:i:s')),array('cuid'=>$shop_info['cuid'],'cid'=>$shop_info['cid']),'shop_user');

		$sid = $this->session->userdata('session_id');
		$sessdata = $this->session->userdata('user_info');
		$result = array("success"=>1,'err_info'=>'','ismain'=>$shop_info['ismain'],'sid'=>$sid,'uid'=>$shop_info['cuid'],'sessdata'=>$sessdata);
		echo json_encode($result);
		return;
	}

	public function logout(){
		$session_data = array(
			"user_info"=>array(
				'c_id' => '',
				'c_name' =>'',
				'c_type' => '',
				'cuname' => '',
				'ismain' => '',
				'c_uid' =>'')
		);
		$this->session->unset_userdata($session_data);
		$this->session->unset_userdata('session_id');
		$sid = $this->session->userdata('session_id');
		$result = array("success"=>1,'err_info'=>'','sid'=>$sid);
		echo json_encode($result);
		return;
	}


	public function orderlist($page_no = 1){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}

		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired','postdata'=>$postdata,'sess_user'=>$sess_user,'sid'=>$sid);
			echo json_encode($result);
			return;
		}

		/*
		if(empty($c_id)){
			alert_redirect(site_url('admin/login'),$this->lang->line('UNLOGIN'));
			return;
		}*/
		$this->data['is_login'] = true;
		$this->data['active'] = 'order';
		$this->data = array_merge((array)$this->data,$this->left_data($c_id));
		//订单总数
		$this->load->model('order_model','order');
		//时间函数
		$begin = date('Y-m-d 00:00:00');
		$end = date('Y-m-d 23:59:59');
		//总订单数
		$this->data['order']['total_count'] = $this->order->get_count("`cid` = {$c_id} AND `status` in (0,1,2,3) AND `createon` >= '{$begin}' AND `createon` <= '{$end}'");
		//派送订单数
		$this->data['order']['sended_count'] = $this->order->get_count("`cid` = {$c_id} AND `status` >=2 AND `createon` >= '{$begin}' AND `createon` <= '{$end}'");
		
		//条件
		//$format = "O.`cid`={$c_id} AND D.`sid`={$c_id} AND O.`status` = %d AND O.`createon` >= '{$begin}' AND O.`createon` <= '{$end}'";
		$format = "O.`cid`={$c_id} AND D.`sid`={$c_id} AND O.`status` = %d ";

		$this->data['order']['data'] = array();

		//初始化一下，不然为空时显示有错误
		$this->data['order']['data']['all_data'] = array();
		//获取订单
		$status = $postdata['status'];
		$count = $this->order->get_count("`cid` = {$c_id}");
		if($count >0){
			$page_no = (int)$page_no;
			$page_no = $page_no <=0 ? 1 : $page_no;
			$data = $this->order->get_orders("O.`cid`={$c_id} AND D.`sid`={$c_id}",$page_no,self::ORDER_PAGE_SIZE,true);
			
			$this->data['order']['data']['all_data'] = $this->format_items($data);
			//分页链接
			$this->data['link_num'] = set_page1($this,site_url("admin/index"),$count,self::ORDER_PAGE_SIZE,3,'',true);
		}
		
		$datanew = array();
		foreach($data as $k => $row){
			if($row['status'] == $status)
				$datanew[] = $row;
		}


		/*
		//未确认订单
		$unconfirm_data = $this->order->get_orders(sprintf($format,0));
		$this->data['order']['data']['unconfirm_data'] = $this->format_items($unconfirm_data);

		//派送中
		$sending_data = $this->order->get_orders(sprintf($format,1));
		$this->data['order']['data']['sending_data'] =$this->format_items($sending_data);

		//已取消订单
		$cancel_data = $this->order->get_orders(sprintf($format,-1));
		$this->data['order']['data']['cancel_data'] = $this->format_items($cancel_data);
		
		//已派送订单
		$sended_data = $this->order->get_orders(sprintf($format,2));
		$this->data['order']['data']['sended_data'] = $this->format_items($sended_data); 
		
		//已完成订单
		$done_data = $this->order->get_orders(sprintf($format,3));
		$this->data['order']['data']['done_data'] = $this->format_items($done_data);
		*/

		$this->data['cusername'] = $this->data['user_info']['cuname'];
		$this->data['seo']['title'] = "商家订单管理";
		log_message('debug', '商户首页'.$c_id);

		$result = array("success"=>1,'err_info'=>'','data'=>$datanew,'sess_user'=>$sess_user,'sid'=>$sid,'postdata'=>$postdata);
		echo json_encode($result);
		//echo json_encode(array('data'=>$datanew));
	
	}

	//取消订单，并更新取消原因，取消时间,取消人，
	public function cancelorder(){
		
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}
		
		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}

		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}



		//post参数
		$status = -1;
		$oid = $postdata['oid'];
		$reason = $postdata['reason'];
		if(empty($oid)){
			$result = array('success'=>0,'err_info'=>'PARAMTER_ERR1');
			echo json_encode($result);
			return;
		}



		//商家详情
		print_r($this->load->model('order_model','order'));
		echo $flag = $this->order->update(array('status'=>$status,'cancelreason'=>$reason,'canceluser'=>'shopper','canceltime'=>date("Y-m-d H:i:s")),array('oid'=>$oid,'cid'=>$c_id));
		if($flag){
			$result = array('success'=>1,'err_info'=>'');
			echo json_encode($result);
			//如果是确认订单就给客户发短信
			//加载配置文件
			$this->config->load('user_config',true);
			$order_status = $this->config->item('orderstatus','user_config');
			$this->log_model->storelog('商铺订单',$oid.' 状态 '.$order_status[$status]);
			return;
		}else{
			$result = array('success'=>0,'err_info'=>'SERVER_ERR');
			echo json_encode($result);
			return;
		}
	
	} 

	/**
	 * 商家登陆 接口
	 * @param $s_name 商家名称
	 * @param $s_pwd 商家密码
	 * @author wenhuijang@sina.com
	 * @return null
	 */
	public function login_check(){
		//post 参数处理
		$data = array();
		$data['username'] = htmlspecialchars($this->input->post('username'),ENT_QUOTES);
		$data['password'] = $this->input->post('password');
		//加载model
		$this->load->model('shop_model','shop');
		//用户名为电话号码、邮箱、字符名称

		$shop_info = $this->shop->get_shop_users(array('U.cuname'=>$data['username']));
		//用户不存在
		if(empty($shop_info) || $shop_info['password'] != md5($data['password'])){
			echo json_encode(array('success'=>0,'err_info'=>$this->lang->line('LOGIN_ERR')));
			return;
		}
		//商家是否待审核
		if($shop_info['confirm'] == -1){
			echo json_encode(array('success'=>0,'err_info'=>$this->lang->line('IS_CONFIRM')));
			return;
		}
		//session
		$session_data = array(
			'c_id' => $shop_info['cid'],
			'c_name' =>$shop_info['cname'],
			'c_type' => $shop_info['ctype'],
			'cuname' => $shop_info['cuname'],
			'c_uid' =>$shop_info['cuid'],
			'c_utype' =>$shop_info['cutype'],
			'ismain' =>$shop_info['ismain'],
			'speed'=>$shop_info['speed']
		);
		$this->session->set_userdata(array('user_info'=>$session_data));
		$this->log_model->storelog('商铺登录','');
		//更新登录时间
		$this->shop->update(array('lastlogin'=>date('Y-m-d H:i:s')),array('cuid'=>$shop_info['cuid'],'cid'=>$shop_info['cid']),'shop_user');
		$result = array("success"=>1,'err_info'=>'','ismain'=>$shop_info['ismain']);
		echo json_encode($result);
		return;
	}

	/**
	 * 商家信息管理
	 * @param $c_id 用户id
	 * @author wenhuijang@sina.com
	 * @version id:1.0 2014-05-20
	 * @return null
	 */
	public function info(){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		//$postdata = json_decode($_POST['json'],true);

		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}
	
		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}
		$this->load->model('shop_model','shop');
		$this->data['is_login'] = true;

			$this->data['info'] = $this->shop->get(array('cid'=>$c_id));
			if(empty($this->data['info'])){
				alert_redirect(site_url('admin/index'),$this->lang->line('SHOP_NOT_EXIST'));
			}
			// $this->data['info']['lowprice'] = !empty($this->data['info']['lowprice'])? explode(',',$this->data['info']['lowprice']) : array();
			$this->data['active'] = 'info';
			//flash UA 导致开启新session
			$this->data['salt'] = self::BATCH_SALT;
			$this->data['flash_tmp'] = substr(md5(self::FlASH_SESS_SALT.'-'.$c_id),6);
			$this->data = array_merge((array)$this->data,$this->left_data($c_id));
			//seo
			$this->data['seo']['title'] = "商家信息设置";
			$result = array("success"=>0,'err_info'=>'User login has expired','data'=>$this->data);
			echo json_encode($result);
			return;

	}

	public function upinfo(){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}
		
		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}

		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}

		//print_r($postdata);

		//post数据
		if($postdata['cname']){
			$data['cname'] = trim($postdata['cname']);
		}
		if($postdata['logopic']){
			$data['logopic'] = $postdata['logopic'];
		}
		//起送价格
		if($postdata['lowprice']){
			$data['lowprice'] = (int)$postdata['lowprice'];
		}
		//起送价说明
		if($postdata['lowpricememo']){
			$data['lowpricememo'] = trim($postdata['lowpricememo']);
		}
		// $data['worktime'] = $this->input->post('worktime');
		//营业时间段
		if($postdata['bworktime1']){
			$data['bworktime1'] = $postdata['bworktime1'];
		}
		if($postdata['eworktime1']){
			$data['eworktime1'] = $postdata['eworktime1'];
		}
		if($postdata['bworktime2']){
			$data['bworktime2'] = $postdata['bworktime2'];
		}
		if($postdata['eworktime2']){
			$data['eworktime2'] = $postdata['eworktime2'];
		}
		if($postdata['announce']){
			$data['announce'] = trim($postdata['announce']);
		}
		if($postdata['address']){
			$data['address'] = trim($postdata['address']);
		}
		if($postdata['summary']){
			$data['summary'] = $postdata['summary'];
		}
		if($postdata['img']){
			$data['img'] = $postdata['img'];
		}
		if($postdata['messaged']){
			$data['messaged'] = (int)$postdata['messaged'];
		}
		//经营范围
		if($postdata['workfor']){
			$data['workfor'] = $postdata['workfor'];
		}
		//口味风格
		if($postdata['cstyle']){
			$data['cstyle'] = $postdata['cstyle'];
		}
		//清真
		if($postdata['ismusilm']){
			$data['ismusilm'] = (int)$postdata['ismusilm'];
		}
		if($postdata['tel']){
			$data['tel'] = $postdata['tel'];
		}
		if($postdata['booked']){
			$data['booked'] = (int)$postdata['booked'];
		}
		if($postdata['invoice']){
			$data['invoice'] = (int)$postdata['invoice'];
		}
		if($postdata['iscredits']){
			$data['iscredits'] = (int)$postdata['iscredits'];
		}
		//超时折扣
		if($postdata['discount']){
			$discount = $postdata['discount'];
			$data['discount'] = $discount == '' ? 0 : $discount;
		}
		//配送速度
		if($postdata['speed']){
			$data['speed'] = (int)$postdata['speed'];
		}
		//配送费
		if($postdata['postage']){
			$data['postage'] = $postdata['postage'];
		}

		$this->load->model('shop_model','shop');
		$this->data['is_login'] = true;

		$this->shop->update($data,array('cid'=>$c_id),'shop');

		$result = array("success"=>1,'err_info'=>'','data'=>$data);
		echo json_encode($result);
		return;

	}

	public function position(){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}
		
		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}
		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}

		//print_r($postdata);

		//post数据
		if($postdata['lng']){
			$data['lng'] = trim($postdata['lng']);
		}
		if($postdata['lat']){
			$data['lat'] = $postdata['lat'];
		}
	
		$this->load->model('shop_model','shop');
		$this->data['is_login'] = true;

		$this->shop->update($data,array('cid'=>$c_id),'shop');

		$result = array("success"=>1,'err_info'=>'','data'=>$data);
		echo json_encode($result);
		return;

	}

	/**
	 * 订单状态更新 interface
	 * @param $c_id 商家ID
	 * @param $status 订单状态值
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-05-20
	 * @return json
	 */
	public function update_order(){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		//$postdata = json_decode($_POST['json'],true);

		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}
	
		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}

		//post参数
		$status = $postdata['status'];
		$oid = $postdata['oid'];
		if(!in_array($status,array(0,1,2,3,-1)) || empty($oid)){
			$result = array('success'=>0,'err_info'=>'PARAMTER_ERR11111111');
			echo json_encode($result);
			return;
		}
		//商家详情
		$this->load->model('order_model','order');
		$flag = $this->order->update(array('status'=>$status),array('oid'=>$oid,'cid'=>$c_id));
		if($flag){
			$result = array('success'=>1,'err_info'=>'','status'=>$status,'oid'=>$oid,'cid'=>$c_id);
			echo json_encode($result);
			//如果是确认订单就给客户发短信
			//加载配置文件
			$this->config->load('user_config',true);
			$order_status = $this->config->item('orderstatus','user_config');
			$this->log_model->storelog('商铺订单',$oid.' 状态 '.$order_status[$status]);
			if ($status == 1)
			{			
				$this->sendsmstocustomer($oid);			
			}
			return;
		}else{
			$result = array('success'=>0,'err_info'=>'SERVER_ERR22222222','oid'=>$oid,'cid'=>$c_id,'status'=>$status,'flag'=>$flag);
			echo json_encode($result);
			return;
		}
	}


	/**
	 * 商品列表管理
	 * @param $c_id 用户id
	 * @author wenhuijang@sina.com
	 * @version id:1.0 2014-05-20
	 * @return null
	 */
	public function foodlist($page_no=1){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}
	
		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}
		//导航数据
		$this->data['is_login'] = true;
		$this->data = array_merge($this->data,(array)$this->left_data($c_id));
		$where = array('cid'=>$c_id);
		//加载model
		$this->load->model('items_model','items');
		$count = $this->items->get_count($where);
		$this->data['food'] = array();
		if($count>0){
			$max_page = ceil($count/self::FOOD_PAGE_SIZE);
			$page_no = intval($page_no);
			$page_no = $page_no<=0 || $max_page<$page_no ? 1 : $page_no;
			$this->data['foods'] = $this->items->get_page($where,$page_no,self::FOOD_PAGE_SIZE);
			$this->data['link_num'] = set_page1($this,site_url("food/index"),$count,self::FOOD_PAGE_SIZE,3,'',true);
		}
		//seo
		$this->data['seo']['title'] = "商家菜品管理";
		//$this->layout->view($this->shop_dir .'/food',$this->data);
			$result = array("success"=>1,'data'=>$this->data);
			echo json_encode($result);
			return;
	}

	public function foodadd(){
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}
	
		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}
		//post 参数
		$data['cid'] = (int) $c_id;
		if($postdata['iname']){
			$data['iname'] = $postdata['iname'];
		}
		if($postdata['flavor']){
			$data['flavor'] = (int)$postdata['flavor'];
		}
		$data['flavor'] = str_replace("，",",",$data['flavor']);
		if($postdata['price']){
			$data['price'] = (float)$postdata['price'];
		}
		if($postdata['category']){
			$data['category'] = $postdata['category'];
		}
		//$data['cataid'] = $this->input->post('selcata');
		if($postdata['memo']){
			$data['memo'] = $postdata['memo'];
		}
		if($postdata['pic1']){
			$data['pic1'] = $postdata['pic1'];
		}
		if($postdata['pic2']){
			$data['pic2'] = $postdata['pic2'];
		}
		if($postdata['pic3']){
			$data['pic3'] = $postdata['pic3'];
		}
		$data['createon'] = date('Y-m-d H:i:s');
		//加载model
		$this->load->model('items_model','items');
		$id = $this->items->add($data);
						/*
						if($id > 0){
														//判断是否是总店
														$ismain = $this->data['user_info']['ismain'];
														//如果是总店 则将菜品插入分店中
														if($ismain)
														{
															//得到所有分店
															$this->load->model('shop_model');
															$slaves = $this->shop_model->gets(array('parentid'=>$data['cid']));
															$slave_items = array();
																			if(!empty($slaves))
																			{
																				foreach($slaves as $one)
																				{
																					$data['cid'] = $one['cid'];
																					$data['parentid'] = $id;
																					array_push($slave_items,$data);
																				}
																				//插入数据库
																				$count = $this->items->insert_batch($slave_items);
																				if($count != count($slave_items))
																				{
																					//log_message('ERROR','Slave company\' items insert err.');
																					$result = array("success"=>0,'err_info'=>'Slave company\' items insert err');
																					echo json_encode($result);
																					return;
																				}
																			}
														}
														//alert_redirect(site_url('food/index'),$this->lang->line('INSERT_SUCCESS'));
														$result = array("success"=>1,'err_info'=>'INSERT_SUCCESS');
														echo json_encode($result);
														return;
						}
						*/
		//alert_redirect(site_url('food/add'),$this->lang->line('INSERT_FAIL'));
		$result = array("success"=>1,'err_info'=>'','data'=>$this->data);
		echo json_encode($result);
		return;
	}

	function sendsmstocustomer($oid)
	{	
		//给店主发短信
		//写入数据库做短信记录
		$this->load->model('order_model');
		$order = $this->order_model->get(array('oid'=>$oid));
		$tel_num  = $order['tel'];
		$msg = '您的订单已被商家'.$order['cname'].'确认制作,详情请登录系统后台查看 要外卖全力为您服务';
		$this->load->model('sms_model');
		$this->sms_model->add(array('sendtype'=>'system','tel'=>$tel_num,'content'=>$msg,'sendtime'=>date("Y-m-d H:i:s")));
		//
		//发送短信
		$this->load->helper('util');
		if(!sendsms($tel_num,$msg))
		{
			$result = array('success'=>0,err_info=>'短信发送失败');
			log_message('ERROR','send sms err');
			return false;
		}
		return true;	
	}

	/**
	 * 更新商家营业状态
	 * @param $c_id 商家ID
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-05-20
	 * @return json
	 */
	public function  update_status(){
		$c_id = isset($this->data['user_info']['c_id']) ? $this->data['user_info']['c_id'] : "";
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		$result = array();
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		if(empty($postdata['session']['uid']) || empty($postdata['session']['sid'])){
			@$postdata['session']['uid'] = $_POST['uid'] ;
			@$postdata['session']['sid'] = $_POST['sid'] ;
		}

		if($sid != $postdata['session']['sid'] || $sess_user['c_uid'] != $postdata['session']['uid']){
			$result = array("success"=>0,'err_info'=>'User login has expired');
			echo json_encode($result);
			return;
		}
		//post参数
		$pause = $postdata['pause'];
		if(!in_array($pause,array(0,1))){
			$result = array('success'=>0,'err_info'=>'error1');
			echo json_encode($result);
			return;
		}
		//商家详情
		$this->load->model('shop_model','shop');
		$flag = $this->shop->update(array('pause'=>$pause),array('cid'=>$c_id),'shop');
		if($flag){
			$result = array('success'=>1,'err_info'=>'');
			echo json_encode($result);
			return;
		}else{
			$result = array('success'=>0,'err_info'=>'error2');
			echo json_encode($result);
			return;
		}
	}

	/**
	 * 获取左侧导航的相关数据
	 * @param $c_id 商家ID
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-05-20
	 * @return json
	 */
	public function left_data($c_id){
		$data = array();
		//商家详情
		$this->load->model('shop_model','shop');
		$data['shop'] = $this->shop->get(array('cid'=>$c_id));
		//时间
		$begin = date('Y-m-d 00:00:00');
		$end = date('Y-m-d 23:59:59');
		
		//订单数据
		$this->load->model('order_model','order');
		//未确认订单
		$data['order']['unconfirm_count'] = $this->order->get_count(array('status' => '0','cid'=>$c_id,'createon >=' => $begin , 'createon <=' => $end));
		//派送中
		$data['order']['sending_count'] = $this->order->get_count(array('status' => '1','cid'=>$c_id,'createon >=' => $begin,'createon <=' => $end));
		
		//评价管理总数
		$this->load->model('comment_model','comment');
		$data['comment']['count'] = $this->comment->get_count(array('sid'=>$c_id));
		//留言管理
		$this->load->model('companymessage_model','message');
		$data['message']['count'] = $this->message->get_count(array('cid'=>$c_id));
		return $data;
	}

	/**
	 * 合并订单详情
	 * @param array $data 
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-05-20
	 * @return array
	 */
	private function format_items($data){
		if(empty($data) || !is_array($data)){
			return false;
		}
		$return = array();
		$this->load->model('companyaction_model');
		$this->load->model('coupon_model');

		foreach($data as $k=>$v){
			$key = $v['oid'];
 				$icon = $v['d_memo']?'<div class="label label-xs label-danger label-padding">一元抢</div>':'no1';
			if(!isset($return[$key])){
				$return[$key] = $v;
				$return[$key]['title'] = $v['iname'] . $v['qty'] .'份'.$icon;
				$return[$key]['msg'] = $v['d_memo'];
				$return[$key]['qty'] = $v['qty'];

				//查询该订单使用过的活动
				$actions = $this->companyaction_model->get_orderaction('and O.oid = ' . $key);
				$return[$key]['actions'] = $actions;
				//得到使用过的优惠券信息
				$coupons = $this->coupon_model->gets(array('memo'=>$key));
				$return[$key]['coupons'] = $coupons;
 			}else{
 				$return[$key]['title'] .=  ' + ' . $v['iname'] . $v['qty'] .'份'.$icon;
 				$return[$key]['msg'] .=  $return[$key]['msg'] !=$v['d_memo'] ? $v['d_memo'] : "";
 				$return[$key]['qty'] += $v['qty'];
 			}
 			unset($key);
		}
		return $return;
	}

	/**
	后台快速登录入口
	这个入口是为了后台人员进入店铺修改订单设立
	@param cid companyid  tel managertel
	*/
    public function bw($cid,$tel)
	{
		$this->load->model('shop_model','shop');
		$where = array('cid'=>$cid,'managertel'=>$tel);
		$tmpshop = $this->shop->get($where);
		if ($tmpshop != false)
		{//清除之前的session
		$session_data = array(
			"user_info"=>array(
				'c_id' => '',
				'c_name' =>'',
				'c_type' => '',
				'cuname' => '',
				'ismain' => '',
				'c_uid' =>'')
			);
		$this->session->unset_userdata($session_data);

		//session
		//var_dump($tmpshop);
		$shop_info = $this->shop->get_shop_users(array('U.cuname'=>$tel));
		$session_data = array(
			'c_id' => $shop_info['cid'],
			'c_name' =>$shop_info['cname'],
			'c_type' => $shop_info['ctype'],
			'cuname' => $shop_info['cuname'],
			'c_uid' =>$shop_info['cuid'],
			'c_utype' =>$shop_info['cutype'],
			'ismain' =>$shop_info['ismain'],
			'speed'=>$shop_info['speed']
		);
		$this->session->set_userdata(array('user_info'=>$session_data));
		//更新登录时间
		$this->shop->update(array('lastlogin'=>date('Y-m-d H:i:s')),array('cuid'=>$shop_info['cuid'],'cid'=>$shop_info['cid']),'shop_user');
        $url = site_url('admin');
		header("Location: $url");
		
		
		}else
		{
		show_error('waring!,hacker attack!');
		
		}
	
	
	}
	/**
	 * 商圈、楼宇、区域选择接口
	 * @param array $data 
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-06-15
	 * @return array
	 */
	public function get_area($type=""){
		//校验登录
		$c_id = $this->data['user_info']['c_id'];
		$sid = $this->session->userdata('session_id');
		$sess_user = $this->session->userdata('user_info');
		if(@$_POST['json']){
			@$postdata = json_decode($_POST['json'],true);	
		}else{
			$postdata = $_POST;
		}

		//post data
		$where['parent'] = $postdata['p_id'];
		$where['level'] = (int)$postdata['level'];
		$where['valid'] = (int)$postdata['valid'];
		//校验参数
		if($where['parent'] < 0 || $where['level'] <=0){
			$result = array('success'=>0,'err_info'=>$this->lang->line('PARAMTER_ERR'));
			echo json_encode($result);
			return;
		}
		//获取商圈或者区域或楼宇
		$this->load->model('area_model','area');
		$data = array();
		if($type == 'building'){
			//商圈条件
			$a_where = 'a.parent='.$where['parent'] .' and a.level='.$where['level'] . ' and a.valid='.$where['valid'];
			// echo $b_where;
			//楼宇条件
			$b_where = 'c.cid= '.$c_id;
			$data = $this->area->area_building($a_where,$b_where);
		}else{
			$data = $this->area->gets($where);
		}
		if(empty($data)){
			$result = array('success'=>0,'err_info'=>$this->lang->line('NO_DATA'));
			echo json_encode($result);
			return;
		}
		$result = array('success'=>1,'err_info'=>'','data'=>$data);
		echo json_encode($result);
		return;
	}

	/**
	 * 店铺配送范围设置
	 * @param array $data 
	 * @author wenhuijang@qq.com
	 * @version id:1.0 2014-06-15
	 * @return array
	 */
	public function area(){
		//是否登录
		$c_id = isset($this->data['user_info']['c_id']) ? $this->data['user_info']['c_id'] : "";
		if(empty($c_id)){
			alert_redirect(site_url('admin/login'),$this->lang->line('UNLOGIN'));
			return;
		}
		$this->load->model('shop_model','shop');
		//获取区域
		$this->load->model('area_model','area_model');
		//是否post提交
		if(!isset($_POST['cid'])){
			//展示店铺
			$this->data['is_login'] = true;
			$this->data['active'] = 'area';
			$this->data = array_merge((array)$this->data,$this->left_data($c_id));
			//商家信息
			$this->data['store'] = $this->shop->get(array('cid'=>$c_id));
			if(empty($this->data['store'])){
				alert_redirect(site_url('admin/index'),$this->lang->line('SHOP_NOT_EXIST'));
				return;
			};

			//校验商圈
			if(empty($this->data['store']['aid'])){
				alert_redirect(site_url('admin/position'),$this->lang->line('NO_SELECTED_AREA'));
				return;
			}

			$this->data['zone'] = $this->area_model->get_pages(array('level'=>4,'valid'=>1),1,100);
			
			// //获取商圈列表
			// $area_info = $this->area_model->get_relation('S.aid = ' . $this->data['store']['aid']);
			// //得到所有平级的区域
			// $related_area = $this->area_model->gets(array('parent ='=>$area_info['m_id'],'valid'=>1));
			// $this->data['area_info'] = $area_info;
			// $this->data['related_area'] = $related_area;
			// print_r($this->data);exit();
			//seo
			$this->data['existarea'] = $this->area_model->get_storearea($c_id);
			$this->data['seo']['title'] = "商家配送范围设置";
			log_message('debug', '商家配送范围设置');
			$this->layout->view($this->shop_dir .'/area',$this->data);	
			return;	
		}
		
		//post参数
		$update = array();
		$update['area'] = trim($this->input->post('area'));
		$update['aid'] = $this->input->post('building');
		if(!empty($update['area'])){
			//获取相应商圈楼宇列表
			$where['parent'] = $update['area'];
			$where['level'] = 6;
			$where['valid'] = 1;
			$buildings = $this->area_model->gets($where); 
			//商圈楼宇配送信息
			$del_ids = array();
			if(!empty($buildings)){
				foreach($buildings as $k=>$v){
					$del_ids[] = $v['aid'];
				}
				$del_id = implode(',',$del_ids);
				//删除相应楼宇所有配送信息
				$del_where = 'aid in ('.$del_id .') and cid='.$c_id;
				$flag = $this->area_model->del($del_where);
				if(!$flag){
					alert_redirect(site_url('admin/area'),$this->lang->line('DELETE_FAIL'));
					return;
				}
			}
			if(!empty($update['aid'])){
				//更新条件
				$u_where = 'aid in ('.implode(',',$update['aid']) .') and valid=1';
				$flag = $this->area_model->insert_company_area($c_id,$u_where);
				if(!$flag){
					alert_redirect(site_url('admin/area'),$this->lang->line('UPDATE_FAIL'));
					return;
				}
			}		
		}
		alert_redirect(site_url('admin/area'),$this->lang->line('UPDATE_SUCCESS'));
		return;
	}
	/**
	商铺用户更改密码
	*/
	function chpwd()
	{
		$c_id = isset($this->data['user_info']['c_id']) ? $this->data['user_info']['c_id'] : "";
		if($oldpwd = $this->input->post('oldpwd'))
		{
					//加载资源文件
			$this->lang->load('user','chinese');
			$newpwd1 = $this->input->post('newpwd1');
			$newpwd2 = $this->input->post('newpwd2');
			$captcha = strtolower($this->input->post('captcha'));
			//先校验验证码
			if($captcha != strtolower($this->session->userdata('pwd_captcha')))
			{
				$result = array('success'=>0,'err_info'=>$this->lang->line('CAPTCHA_ERR'));
				exit(json_encode($result));
			}
			//加载model
			$this->load->model('shop_model','shop');
			$shop_info = $this->shop->get_shop_users(array('U.cid'=>$c_id));
			if(!$shop_info)
			{
				$this->session->sess_destroy();
				$result = array('success'=>0,'err_info'=>$this->lang->line('SESS_EXPIRED'));
				exit(json_encode($result));
			}	
			if(md5($oldpwd) != $shop_info['password'])
			{
				$result = array('success'=>0,'err_info'=>$this->lang->line('PASSWORD_ERR'));
				exit(json_encode($result));
			}
			if($newpwd2 != $newpwd1)
			{
				$result = array('success'=>0,'err_info'=>$this->lang->line('PWD_NOT_SAME'));
				exit(json_encode($result));
			}	
			//修改密码
			if($this->shop->update_shop_user(array('cid'=>$c_id),array('password'=>md5($newpwd1))))
			{
				$result = array('success'=>1);
				exit(json_encode($result));
			}			
		}
		else
		{
			if(empty($c_id))
			{
				alert_redirect(site_url('admin/login'),$this->lang->line('UNLOGIN'));
				return;
			}
				//展示店铺
			$this->load->model('shop_model','shop');
			$this->data = array_merge((array)$this->data,$this->left_data($c_id));
			$this->data['is_login'] = true;	
			$this->data['title'] = '密码更改管理';
			$this->data['active'] = 'chpwd';		
			//生成验证码
			$this->load->helper('util');
			$captcha = generate_captcha($this);
			$this->session->set_userdata('pwd_captcha',$captcha['word']);
			$this->data['img'] = $captcha['time'] . '.jpg';
			$this->layout->view('shop/chpwd',$this->data);	
		}	
	
	}
	
	/**
	 * 分店列表
	 * @param array $data 
	 * @author waaron
	 * @version id:1.0 2014-06-16
	 * @return array
	 */
	function slave_shop()
	{
		//得到是否是总店
		$ismain = $this->data['user_info']['ismain'];
		$cid = $this->data['user_info']['c_id'];
		//不是总店
		if(empty($cid))
		{
			alert_redirect(site_url('admin/login'));
			return;
		}
		if($ismain == 0)
		{
			alert_redirect(site_url('admin/index'));
			return;
		}
		//查询该总店的所有分店
		$this->load->model('shop_model');
		$count = $this->shop_model->get_count(array('parentid'=>$cid));
		if($count > 0)
		{
			//得到一页的记录
			$page_no = (int)$this->uri->segment(3);
			if($page_no <= 0)
			{
				$page_no = 1;
			}
			$this->data['cur_page'] = $this->shop_model->get_page(array('parentid'=>$cid),$page_no,self::SLAVE_PAGE_SIZE);
			//得到分页
			$this->load->helper('util');
			$this->data['num_link'] = set_page1($this,site_url('admin/slave_shop'),$count,self::SLAVE_PAGE_SIZE,3,'',true);
		}
		$this->data['title'] = '连锁店管理';
		$this->data['active'] = 'slave_shop';
		log_message('debug', '连锁店管理');
		$this->layout->view('shop/slave_shop',$this->data);
	}
	
	/**
	 * 禁用分店
	 * @author aaron
	 * @version id:1.0 2014-06-16
	 * @return array
	 */
	function forbidden()
	{
		//得到是否是总店
		$ismain = $this->data['user_info']['ismain'];
		$cid = $this->data['user_info']['c_id'];
		//不是总店
		if($ismain == 0 || empty($cid))
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('NO_DATA'));
			exit(json_encode($result));
		}
		$slave_id = $this->input->post('slave_id');
		$confirm = $this->input->post('is_confirm');
		if(!$slave_id)
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('PARAMTER_ERR'));
			exit(json_encode($result));
		}
		//查询分店信息
		$this->load->model('shop_model');
		$slave = $this->shop_model->get(array('cid'=>$slave_id));
		if(!$slave || $slave['parentid'] != $cid)
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('NO_DATA'));
			exit(json_encode($result));
		}
		//禁用分店
		if($this->shop_model->update(array('confirm'=>$confirm),'cid = ' . $slave_id,'shop'))
		{
			$result = array('success'=>1);
			exit(json_encode($result));
		}
		$result = array('success'=>0,'err_info'=>$this->lang->line('SERVER_ERR'));
		exit(json_encode($result));
	}
	
	/**
	 * 重置分店用户密码
	 * @author aaron
	 * @version id:1.0 2014-06-16
	 * @return array
	 */
	function reset_slave()
	{
		//得到是否是总店
		$ismain = $this->data['user_info']['ismain'];
		$cid = $this->data['user_info']['c_id'];
		//不是总店
		if($ismain == 0 || empty($cid))
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('NO_DATA'));
			exit(json_encode($result));
		}
		$slave_id = $this->input->post('slave_id');
		
		if(!$slave_id)
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('PARAMTER_ERR'));
			exit(json_encode($result));
		}
		//查询分店信息
		$this->load->model('shop_model');
		$slave = $this->shop_model->get(array('cid'=>$slave_id));
		if(!$slave || $slave['parentid'] != $cid)
		{
			$result = array('success'=>0,'err_info'=>$this->lang->line('NO_DATA'));
			exit(json_encode($result));
		}

		//重置分店用户密码
		$this->shop_model->update(array('password'=>md5('000000')),'cid = ' . $slave_id,'shop_user');
		$result = array('success'=>1);
		exit(json_encode($result));
		log_message('ERROR','Reset the password of the slave shop ' . $slave_id . ' error.');
	}
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */